package com.gowants.pems.service;

import java.util.List;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.gowants.pems.mapper.SysMapper;
import com.gowants.pems.model.Sys;
import com.gowants.pems.util.RedisUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@Service(value = "SysService")
public class SysService extends BaseService<Sys> {

	@Autowired
	private SysMapper SysMapper;
	@Autowired
	private ParamsService paramsService;
	@Autowired
	private RedisUtils redisUtils;
	/**
	 * key 前缀，防止和其他地方的key可以冲突
	 */
	@Value("${gowants.redisKey}")
	private String redisKey;
	@Override
	public int save(Sys record) {
		// TODO Auto-generated method stub
		return SysMapper.save(record);
	}

	@Override
	public int delete(String primaryKey) {
		// TODO Auto-generated method stub
		return SysMapper.delete(primaryKey);
	}

	@Override
	public int update(Sys record) {
		// TODO Auto-generated method stub
		int i=0;
		i= SysMapper.update(record);
		if(i>0) {
			Object codeJsons = redisUtils.get(redisKey+"sys:" + record.getId());
			if (null != codeJsons) {
				redisUtils.del(redisKey+"sys:" + record.getId());
			}
			Sys ec= SysMapper.selectOne(record.getId());
			Random r = new Random();
			redisUtils.set(redisKey+"sys:" + record.getId(), JSON.toJSON(ec), r.nextInt(999999));	
		}
		return i;
	}

	@Override
	public Sys selectOne(String primaryKey) {
		// TODO Auto-generated method stub
		String codeJson = "";
		Object codeJsons = redisUtils.get(redisKey+"sys:" + primaryKey);
		if (null != codeJsons) {
			codeJson = codeJsons.toString();
		}
		if (StringUtils.isNotBlank(codeJson)) {
			Sys ec = JSONObject.parseObject(codeJson, Sys.class);
			return ec;
			
		}else {
			Sys ec= SysMapper.selectOne(primaryKey);
			if (null != ec) {
				Random r = new Random();
				redisUtils.set(redisKey+"sys:" + primaryKey, JSON.toJSON(ec), r.nextInt(999999));
				return ec;
			}
		}
		
		return null;
	}

	@Override
	public List<Sys> select(Sys record) {
		// TODO Auto-generated method stub
		return SysMapper.select(record);
	}

	@Override
	public int getCount(Sys record) {
		// TODO Auto-generated method stub
		return 0;
	}

	/**
	 * 通过附件ID获取附件保存地址
	 * 
	 * @param accessoriesId
	 * @return
	 */
	public String getSaveAddress(String accessoriesId) {
		String saveAddress = paramsService.getParamValueByNumber(accessoriesId);
		return saveAddress;
	}
}
